package com.youclk.exam.service.impl;

import com.youclk.exam.entity.Category;
import com.youclk.exam.repository.CategoryRepository;
import com.youclk.exam.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public void printCategory() {
        long start = System.currentTimeMillis();
        HashMap<Integer, ArrayList<Category>> map = new HashMap<>();
        Integer[] groupIds = categoryRepository.getGroupIds();
        for (Integer groupId : groupIds) {
            map.put(groupId, categoryRepository.getGroup(groupId));
        }
        float executeQueryTime = (System.currentTimeMillis() - start) / 1000f;

        StringBuilder sb = new StringBuilder();
        sb.append("---------------------------------------------------\n");
        sb.append(String.format("查询数据库耗时：%.3fs\n", executeQueryTime));
        sb.append("---------------------------------------------------\n");
        sb.append("所有分类\n");

        for (Category category : map.get(0)) {
            sb.append(String.format("--%s\n", category.getGcName()));
            recursive("--", sb, category, map);
        }

        System.out.println(sb.toString());
    }

    private void recursive(String joint, StringBuilder sb, Category category, HashMap<Integer, ArrayList<Category>> map) {
        ArrayList<Category> childList = map.get(category.getGcId());
        if (childList != null) {
            joint += "--";
            for (Category child : childList) {
                sb.append(String.format("%s%s\n", joint, child.getGcName()));
                if (map.get(child.getGcId()) != null)
                    recursive(joint, sb, child, map);
            }
        }
    }
}
